package chapter1.util;

import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 工具类-单例工厂
 *
 * @author 郑植航
 * @since 2025/6/15 15:35
 */
public class SingletonFactory {

    private static final Map<Class<?>,Object> instanceMap = new ConcurrentHashMap<>();

    public static <T> T  getInstance(Class<T> clazz) {

        if (clazz == null) {
            throw new IllegalArgumentException("未知的类型");
        }
        if (!instanceMap.containsKey(clazz)) {
            try {
                Constructor<T> constructor = clazz.getDeclaredConstructor();
                constructor.setAccessible(true);
                T singleton = constructor.newInstance();
                instanceMap.put(clazz, singleton);

            } catch (Exception e) {
                throw new IllegalArgumentException("创建单例模式失败，" + clazz.getSimpleName(), e);
            }
        }
        @SuppressWarnings("unchecked")
        T instance = (T)instanceMap.get(clazz);
        return instance;


    }
}
